import pygtk
pygtk.require('2.0')
import gtk
import os, string, random, time, sys

from mbac.util.gtkutil import getScrolledWidget
from mbac.gui.modaldialog import ModalDialog

class MainPage(gtk.VBox):

    # instance variables
    counter = 0
    randomValue = ""
    clockStart = 0
    
    # constant values
    # I have to change them when rows and tries will be customizable
    maxTry = 8
    maxDigit = 4
    
    def getRandomValue(self):
        # we need a number of different digits
        while True:
            valTmp = string.zfill(str(random.randint(1,int(string.rjust("9",self.maxDigit,"9")))),self.maxDigit)
            #print valTmp
            isValidNumber = True 
            for x in range(0,self.maxDigit):
                #print x
                if string.count(valTmp, valTmp[x]) > 1:
                    isValidNumber = False
                    break
            if isValidNumber:
                return valTmp
            
        
    def cleanLabels(self):
        for x in range(0,self.maxTry):
            self.lblDigit[x].set_text("")
            self.lblResult[x].set_text("")
    
    def cleanEntry(self, widget):
        self.entryDigit.set_text("")
    
    def virtualKeyboardStatus(self, value):
        for x in range(0,10):
            self.btVirtualKeyboard[x].set_sensitive(value)
            
    def start(self, widget):
        
        # check number try and number digit
        try:
            self.maxTry = int(self.configPage.entryTry.get_text())
        except:
            print str(sys.exc_info()[0])
            print str(sys.exc_info()[1])
            modal = ModalDialog("No valid try entry")
            return None
        
        try:
            self.maxDigit = int(self.configPage.entryDigit.get_text())
        except:
            print str(sys.exc_info()[0])
            print str(sys.exc_info()[1])
            modal = ModalDialog("No valid digit entry")
            return None

        # building schema
        self.buildResultWidget()

        self.btStart.set_sensitive(False)
        self.btEnd.set_sensitive(True)
        self.btVerifyDigit.set_sensitive(True)
        self.virtualKeyboardStatus(True)
        self.randomValue = self.getRandomValue()
        self.clockStart = time.time()
        print(self.randomValue)
        
        self.cleanLabels()
        self.resetVariables()

    def end(self, widget):
        modal = ModalDialog("Digits " + self.randomValue)
        self._end()
    
    def _end(self):
        self.btStart.set_sensitive(True)
        self.btEnd.set_sensitive(False)
        self.btVerifyDigit.set_sensitive(False)
        self.virtualKeyboardStatus(False)

    def resetVariables(self):
        self.counter = 0;

    def insertDigit(self, widget, value):
        self.entryDigit.set_text(self.entryDigit.get_text() + value)

    def verifyDigit(self, widget):

        text = self.entryDigit.get_text()
        # 
        textTmp = ""
        randomTmp = ""
        # valueBull >> correct digit position
        # valueCow >> correct digit wrong position
        
        valueBull = 0
        valueCow = 0
        
        try:
            digits = int(text)
            
            if len(self.entryDigit.get_text()) != self.maxDigit:
                 modal = ModalDialog("Insert " + str(self.maxTry) + " digits")
            else:
                
                # check user insert different digits
                for x in range(0, self.maxDigit):
                    cntSameDigit = string.count(text, text[x])
                    if cntSameDigit > 1:
                        modal = ModalDialog("Insert different digits")
                        return
                
                for x in range(0,self.maxDigit):
                    if self.randomValue[x] == text[x]:
                        valueBull = valueBull + 1
                    else:
                        textTmp = textTmp + text[x]
                        randomTmp = randomTmp + self.randomValue[x]
                
                # we have to loop to find correct digit in wrong position
                for x in range(0,len(textTmp)):
                    valueCow = valueCow + string.count(randomTmp, textTmp[x])
                    
                #print valueBull
                #print valueCow
                
                self.lblDigit[self.counter].set_text(self.entryDigit.get_text())
                self.lblResult[self.counter].set_text(str(valueBull) + "B" + str(valueCow) + "C")
                
                self.counter = self.counter + 1
                
                if valueBull == self.maxDigit:
                    # diff time
                    usedTime = time.time() - self.clockStart
                    modal = ModalDialog("You win in " + str(int(usedTime)) + " sec")
                    self._end()
                elif self.counter == self.maxTry:
                    modal = ModalDialog("You lose - Val " + str(self.randomValue))
                    self._end()
            
        except ValueError:
            # some char is not a digit
            modal = ModalDialog("No valid char")
                
        self.entryDigit.set_text("")

        # we have to loop for every char and find:
        # if char is in correct position
        # if char exists in wrong position        
        

    def buildResultWidget(self):

        # try to move children
        listChildren = self.vLabelsDataBox.get_children()
        
        self.entryDigit.set_max_length(self.maxDigit)
        self.entryDigit.set_text("")
        
        for x in range(0,len(listChildren)):
            self.vLabelsDataBox.remove(listChildren[x])
         
        lblTry = []
        self.lblDigit = []
        self.lblResult = []
        hLabelsDataBox = []

        for x in range(0,self.maxTry):

            lblTry.append(gtk.Label(str(x+1)))
            lblTry[x].show()
            self.lblDigit.append(gtk.Label(""))
            self.lblDigit[x].show()
            self.lblResult.append(gtk.Label(""))
            self.lblResult[x].show()
            hLabelsDataBox.append(gtk.HBox(False,5))
            hLabelsDataBox[x].show()
            hLabelsDataBox[x].pack_start(lblTry[x], False, False, 5)
            hLabelsDataBox[x].pack_start(self.lblDigit[x], False, False)
            hLabelsDataBox[x].pack_start(self.lblResult[x], False, False)
            self.vLabelsDataBox.pack_start(hLabelsDataBox[x], False, False, 0)
        
    def build(self):

        # building page
        # parameter homogeneous, spacing
        hEntryDigitBox = gtk.HBox(False,10)
        hEntryDigitBox.show()
        
        lblInput = gtk.Label("Input:")
        lblInput.show();
        
        self.entryDigit = gtk.Entry()
        self.entryDigit.show()
        self.entryDigit.set_sensitive(False)
        
        self.btVerifyDigit = gtk.Button("Ok")
        self.btVerifyDigit.connect("clicked", self.verifyDigit)
        self.btVerifyDigit.set_sensitive(False)
        self.btVerifyDigit.show()
        
        hEntryDigitBox.pack_start(lblInput, False, False, 0)
        hEntryDigitBox.pack_start(self.entryDigit, True, True, 0)
        hEntryDigitBox.pack_start(self.btVerifyDigit, False, False, 0)

        self.vLabelsDataBox = gtk.VBox(False, 10)
        self.vLabelsDataBox.show()
                
        # put vbox in scrolled widget
        scrolledWidget = getScrolledWidget()
        scrolledWidget.add_with_viewport(self.vLabelsDataBox) # if we use a non scrollable widget we need add_with_viewport
        scrolledWidget.show()

        # calling dynamic resultWidget
        self.buildResultWidget()
        
        ## begin virtual keyboard
        hVirtualKeyboardBox1 = gtk.HButtonBox()
        hVirtualKeyboardBox1.set_layout(gtk.BUTTONBOX_SPREAD)
        hVirtualKeyboardBox1.show()
        
        hVirtualKeyboardBox2 = gtk.HButtonBox()
        hVirtualKeyboardBox2.set_layout(gtk.BUTTONBOX_SPREAD)
        hVirtualKeyboardBox2.show()
        
        self.btVirtualKeyboard = []
        
        # build virtual keyboard
        for x in range (0,5):
            self.btVirtualKeyboard.append(gtk.Button(str(x)))
            self.btVirtualKeyboard[x].show()
            hVirtualKeyboardBox1.pack_start(self.btVirtualKeyboard[x], True, True,5)
            self.btVirtualKeyboard[x].connect("clicked", self.insertDigit, str(x))
            self.btVirtualKeyboard[x].set_sensitive(False)
            

        for x in range (5,10):
            self.btVirtualKeyboard.append(gtk.Button(str(x)))
            self.btVirtualKeyboard[x].show()
            hVirtualKeyboardBox2.pack_start(self.btVirtualKeyboard[x], True, True,5)
            self.btVirtualKeyboard[x].connect("clicked", self.insertDigit, str(x))
            self.btVirtualKeyboard[x].set_sensitive(False)
        
        ## end virtual keyboard
            
        hButtonsBox = gtk.HButtonBox()
        hButtonsBox.set_layout(gtk.BUTTONBOX_SPREAD)
        hButtonsBox.show()
        
        self.btStart = gtk.Button("Start")
        self.btStart.connect("clicked", self.start)
        self.btStart.show()
        self.btEnd = gtk.Button("End")
        self.btEnd.connect("clicked", self.end)
        self.btEnd.set_sensitive(False)
        self.btEnd.show()
        self.btClean = gtk.Button("Clean")
        self.btClean.connect("clicked", self.cleanEntry)
        self.btClean.show()
        
        hButtonsBox.pack_start(self.btStart, False, False, 0)
        hButtonsBox.pack_start(self.btEnd, False, False, 0)
        hButtonsBox.pack_start(self.btClean, False, False, 0)
        
        self.pack_start(hEntryDigitBox, False, False, 0)
        self.pack_start(scrolledWidget, True, True, 10)
        self.pack_start(hVirtualKeyboardBox1, False, False,0)
        self.pack_start(hVirtualKeyboardBox2, False, False,0)
        self.pack_start(hButtonsBox, False, False,0)
        
    def __init__(self, configPage):
        
        # reference global to configPage
        self.configPage = configPage
        
        gtk.VBox.__init__(self, False, 5)

        self.build()
        self.show()